<?php

namespace app\share\model;

use think\Db;
use think\Model;
use think\Loader;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

class UploadImg extends Model
{
    protected $STATUS_Local = 1;//本地上传
    protected $STATUS_OtherServer = 2;//第三方服务器
    protected $STATUS_QiNiu = 3;//七牛上传

    public function __construct()
    {
        parent::__construct();
        //引入extend里面的类
        Loader::import('Qiniu.autoload');
    }
    //图片上传$file文件
    public function uploadPicture($file)
    {
        $arr_suffix = ['jpg', 'jpeg', 'png', 'gif'];
        $img_suffix = strtolower( pathinfo( $file['name'],PATHINFO_EXTENSION ) );
        if( !in_array( $img_suffix, $arr_suffix, true ) )
        {
            return ['code'=>-2001, 'msg'=>"图片格式不合法,仅支持jpg、jpeg、png、gif图片"];
        }
        if($file['size'] > 102400)
        {
            return ['code'=>-2002, 'msg'=>"图片大小不合法,不能超过100kb"];
        }
        if ($file['error'] == 0)
        {
            $fileame = date("YmdHis").uniqid("qc").".".pathinfo($file['name'],PATHINFO_EXTENSION);
            $res = Db::name("sys_setup")->field("sys_upload_picture_set")->where(['sys_id'=>1])->find();
            if($res === NULL || $res['sys_upload_picture_set'] === $this->STATUS_Local)
            {
                return self::uploadLocal($file,$fileame);
            }else
            {
                if($res['sys_upload_picture_set'] === $this->STATUS_OtherServer)
                {
                    return self::uploadImg($file,$fileame);
                }else if($res['sys_upload_picture_set'] === $this->STATUS_QiNiu)
                {
                    return self::uploadQiNiu($file,$fileame);
                }else
                {
                    return ['code'=>'-2005','msg'=>'图片上传配置有误,请检查后重试'];
                }
            }
        }
    }
    /**
     * 图片上传七牛云配置
     */
    private function uploadQiNiu($file,$fileame)
    {
        $path = $file['tmp_name'];
        $ak = config('QiNiu')['ACCESSKEY'];
        $sk = config('QiNiu')['SECRETKEY'];
        // 构建鉴权对象
        $auth = new Auth($ak,$sk);
        // 要上传的空间
        $bucket = config('QiNiu')['BUCKET'];
        $img_domain = config('QiNiu')['DOMAIN'];
        $token = $auth->uploadToken($bucket);
        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, $fileame, $path);
        if ($err !== null) {
            return ['code'=>-2004, 'msg'=>$err, 'data'=>['url'=>'null']];
        } else {
            //返回图片的完整URL
            return ['code'=>200, 'msg'=>'上传成功', 'data'=>['img_url'=>'/'.$ret['key'], 'img_domain'=>$img_domain, 'way'=>"七牛云存储"]];
        }
    }

    /**
     * 图片上传第三方图片服务器
     * @param   file
     * @return  string
     */
    private function uploadImg($file, $filename)
    {
        $path = './'.$filename;
        $moveRs = move_uploaded_file($file['tmp_name'],$path);
        //上传到其他服务器
        $url = config('img_url');
        if($moveRs){
            $rs = self::http_curl($path,$url);
            //删除本地服务器图片,只保留远端图片资源
            unlink($path);
            return ['code'=>200, 'msg'=>'上传成功', 'data'=>['img_url'=>$rs,'img_domain'=>$url, 'way'=>"独立云存储"]];
        }
    }
    private function uploadLocal($file, $filename)
    {
        $path = ROOT_PATH."public".DS."uploads".DS.date('Ymd').DS; //文件存储路径设置
        if(!file_exists($path))
        {
            mkdir($path,0777,true);
        }
        $path = $path.$filename;
        $moveRs = move_uploaded_file($file['tmp_name'],$path);
        if($moveRs){
            $rs = str_replace("\\", '/', DS."uploads".DS.date('Ymd').DS.$filename);
            $url = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME'];
            return ['code'=>200, 'msg'=>'上传成功', 'data'=>['img_url'=>$rs,'img_domain'=>$url, 'way'=>"本地云存储"]];
        }
    }

    private function http_curl($path,$url){
        $curl = curl_init();
        if (class_exists('\CURLFile')) {
            curl_setopt($curl, CURLOPT_SAFE_UPLOAD, TRUE);
            $data = array('file' => new \CURLFile(realpath($path)));//>=5.5
        }else{
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($curl, CURLOPT_SAFE_UPLOAD, FALSE);
            }
            $data = array('file' => '@' . realpath($path));//<=5.5
        }

        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);  //ssl 这两行代码是为了能走https的请求,http请求放着也没有影响
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); //ssl 这两行代码是为了能走https的请求,http请求放着也没有影响

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1 );
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_USERAGENT,"TEST");
        $result = curl_exec($curl);
        return $result;
    }


}